//
//  dvd.m
//  Rainbow
//
//  Created by Alex on 21/07/09.
//  Copyright 2009 Erasmus Software. All rights reserved.
//

#import "dvd.h"

@implementation Dvd

- (id) init
{
	self = [super init];
	if (self != nil)
	{
		_dvds = [[NSMutableArray alloc] init];
		_oldDvds = [[NSMutableArray alloc] init];
		_XMLTree = [[XMLInterface alloc] initPars];
		[_XMLTree loadDvd:_dvds];
	}
	return self;
}

- (int) count
{
	return [_dvds count];
}

-(NSDictionary*) itemAtIndex:(int)index
{
	return [_dvds objectAtIndex:index];
}

- (void) addDvdWithTitle:(NSString *)title director:(NSString *)director year:(NSString*)year language:(NSString*)language type:(NSString*)type 
				   actor:(NSString*)actor summary:(NSString*)summary comment:(NSString *)comment tags:(NSString*)tags path:(NSString*)path
{
	NSDictionary	*dvd = [NSDictionary alloc];
	NSString		*new_id;

	[title retain];
	[director retain];
	[year retain];
	[language retain];
	[type retain];
	[actor retain];
	[summary retain];
	[comment retain];
	[tags retain];
	[path retain];
	new_id = [NSString stringWithFormat:@"%d", [_XMLTree getNewId]];
	[new_id retain];
	dvd = [NSMutableDictionary	dictionaryWithObjectsAndKeys:new_id, kId, title, kTitle, director, kDirector, language, kLanguage, year, kYear, type, kType, actor, kActor, summary, kSummary, comment, kComment, tags, kTags, path, kPath, nil];
	[_XMLTree addDvd:dvd];          
	[_dvds addObject:dvd];
	[_XMLTree save];
}

- (void) removeItemAtIndex:(unsigned int)index
{
	[_XMLTree deleteDvd:[[[_dvds objectAtIndex:index]valueForKey:kId] integerValue]];
	[_dvds removeObjectAtIndex:index];
	[_XMLTree setDvdOwner:@"p"];
	[_XMLTree save];
}

- (void) changeDvdAtIndex:(unsigned int)index item:(NSDictionary*)item
{	
	NSInteger	idObj;

	[item retain];
	idObj = [[[_dvds objectAtIndex:index] valueForKey:kId] integerValue];
	[_XMLTree deleteDvd:idObj];
	[_XMLTree addDvd:item];
	[_dvds replaceObjectAtIndex:index withObject:item];
	[_XMLTree save];
}


- (NSString *) reinitialize
{
	NSString *searchlabel = NULL;
	
	if ([_oldDvds count])
	{
		[_dvds removeAllObjects];
		[_dvds addObjectsFromArray:_oldDvds];		
		[_oldDvds removeAllObjects];
	}
	
	searchlabel = [[NSString alloc] initWithString:@"Search"];
	
	return searchlabel;
}

- (NSString *) updatewithPredicate:(NSPredicate *)regexp
{
	NSString *searchlabel = NULL;

	if (![_oldDvds count])		
		[_oldDvds addObjectsFromArray:_dvds];
	else
	{
		[_dvds removeAllObjects];
		[_dvds addObjectsFromArray:_oldDvds];
	}
	[_dvds filterUsingPredicate:regexp];
	
	searchlabel = [[NSString alloc] initWithFormat:@"%d of %d", [_dvds count], [_oldDvds count]];
	
	return (searchlabel);
}

- (void)	setDvdOwner:(NSString *)owner
{
	[_XMLTree setDvdOwner:owner];
}

- (void) dealloc
{
	[_dvds release];
	[_oldDvds release];
	[_XMLTree release];
	[super dealloc];
}

@end

